from rest_framework.views import APIView
from django.contrib.auth import get_user_model
from django.contrib.auth import login
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from ..utils.response_utils import api_response, ResponseCode  # 你的自定义返回工具
import json

Adminer = get_user_model()


class LoginView(APIView):
    """
    管理员登录接口
    """

    @swagger_auto_schema(
        operation_description="登录接口：传入用户名和密码",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=["username", "password"],
            properties={
                "username": openapi.Schema(type=openapi.TYPE_STRING, description="用户名"),
                "password": openapi.Schema(type=openapi.TYPE_STRING, description="密码"),
            }
        ),
        responses={
            200: openapi.Response(
                description="登录成功",
                schema=openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        "code": openapi.Schema(type=openapi.TYPE_INTEGER, description="状态码"),
                        "message": openapi.Schema(type=openapi.TYPE_STRING, description="返回信息"),
                        "data": openapi.Schema(
                            type=openapi.TYPE_OBJECT,
                            properties={
                                "username": openapi.Schema(type=openapi.TYPE_STRING, description="用户名"),
                            }
                        )
                    }
                )
            ),
            401: openapi.Response(description="用户名或密码错误"),
        },
        tags=["后台登录"]
    )
    def post(self, request):
        try:
            data = json.loads(request.body.decode("utf-8"))
            username = data.get("username")
            password = data.get("password")

            if not username or not password:
                return api_response(ResponseCode.BAD_REQUEST, "用户名和密码不能为空")

            try:
                user = Adminer.objects.get(username=username)
                if user.password == password:
                    login(request, user)
                    return api_response(ResponseCode.SUCCESS, "登录成功", {"username": user.username})
                else:
                    return api_response(ResponseCode.UNAUTHORIZED, "密码错误")
            except Adminer.DoesNotExist:
                return api_response(ResponseCode.NOT_FOUND, "用户不存在")

        except Exception as e:
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, str(e))
